<template>
  <el-dialog v-drag width="45%" :title="!dataForm.userId ? '新增用户' : '修改用户'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm"  :inline="true" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="用户名" prop="userName">
        <el-input size="mini" v-model="dataForm.userName" placeholder="登录帐号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.userId }">
        <el-input size="mini" v-model="dataForm.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.userId }">
        <el-input size="mini" v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input size="mini" v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input size="mini" v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input size="mini" v-model="dataForm.address" placeholder="地址"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input size="mini" v-model="dataForm.age" placeholder="年龄"></el-input>
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <!-- <el-select size="mini" @focus="getDicts('USER_TYPE')"  v-model="dataForm.userType" clearable placeholder="请选择">
          <el-option v-for="item in userTypes" :key="item.value" :label="item.label" :value="item.label">
          </el-option>
        </el-select> -->
        <el-select size="mini"  v-model="dataForm.userType" clearable placeholder="请选择">
          <el-option value="0">系统用户</el-option>
          <el-option value="1">门店用户</el-option>
          <el-option value="2">商城用户</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio size="mini" :label="0">禁用</el-radio>
          <el-radio size="mini" :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="角色" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox size="mini" v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="visible = false">取消</el-button>
      <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    isEmail,
    isMobile
  } from '@/utils/validate'
  export default {
    data() {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.userId && !/\S/.test(value)) {
          callback(new Error('密码不能为空'))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.userId && !/\S/.test(value)) {
          callback(new Error('确认密码不能为空'))
        } else if (this.dataForm.password !== value) {
          callback(new Error('确认密码与密码输入不一致'))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        roleList: [],
        userTypes: [],
        dataForm: {
          userId: undefined,
          userName: '',
          password: '',
          comfirmPassword: '',
          salt: '',
          email: '',
          mobile: '',
          roleIdList: [],
          status: 1
        },
        dataRule: {
          userName: [{
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
          }],
          password: [{
            validator: validatePassword,
            trigger: 'blur'
          }],
          comfirmPassword: [{
            validator: validateComfirmPassword,
            trigger: 'blur'
          }],
          email: [{
              required: true,
              message: '邮箱不能为空',
              trigger: 'blur'
            },
            {
              validator: validateEmail,
              trigger: 'blur'
            }
          ],
          mobile: [{
              required: true,
              message: '手机号不能为空',
              trigger: 'blur'
            },
            {
              validator: validateMobile,
              trigger: 'blur'
            }
          ]
        }
      }
    },
    methods: {
      async init(userId) {
        this.dataForm.userId = userId
        const {
          data
        } = await this.$http({
          url: '/sys/role/select',
          method: 'get',
          params: this.$http.adornParams()
        })
        this.roleList = data && data.code === 0 ? data.list : [],
          this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })

        if (this.dataForm.userId) {
          this.$http({
            url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.userId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.dataForm.userName = data.user.username
              this.dataForm.salt = data.user.salt
              this.dataForm.email = data.user.email
              this.dataForm.mobile = data.user.mobile
              this.dataForm.roleIdList = data.user.roleIdList
              this.dataForm.status = data.user.status
            }
          })
        }
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (valid) {
            const {
              data
            } = await this.$http({
              url: this.$http.adornUrl(`/sys/user/${!this.dataForm.userId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'userId': this.dataForm.userId || undefined,
                'username': this.dataForm.userName,
                'password': this.dataForm.password,
                'salt': this.dataForm.salt,
                'email': this.dataForm.email,
                'mobile': this.dataForm.mobile,
                'status': this.dataForm.status,
                'roleIdList': this.dataForm.roleIdList
              })
            })

            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          }
        })
      },
      async getDicts(type) {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': type
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          if(type === 'USER_TYPE'){
            this.userTypes = data.data
          }

        }
      },
    }
  }
</script>
